import { message } from "@/utils/message";
import { getStudentInto } from "@/api/user";
import {
  onStartExamByStudent,
  onStopExamByStudent,
  findProducePaperQuestionById,
  updateStudentProduceExamAnswer,
  sendPhoto,
  closeSseClient
} from "@/api/produceexam";
import { ref, onMounted, onUnmounted, watch, computed } from "vue";
import { closeAllDialog } from "@/components/ReDialog";
import { ElMessageBox } from "element-plus";
import { type FormItemProps, type FormExamProps } from "../utils/types";
import { countDown } from "./timer";
import adapter from "webrtc-adapter";
import { EventSourcePolyfill } from "event-source-polyfill";
import { getToken } from "@/utils/auth";
import { sseUrlApi } from "@/api/utils";
import { emitter } from "@/utils/mitt";

export function useForm() {
  console.log(adapter.browserDetails.browser);
  console.log(adapter.browserDetails.version);

  const { showTime } = countDown();
  const isShowStopDialog = ref(false);
  const taskRef = ref();
  const studentColumns = ref([]);

  function setFormInlineToTsx(data?: FormItemProps) {
    taskRef.value = data;
  }

  const answerSheetList = ref([]);

  async function onGetUserInfo() {
    getStudentInto().then(res => {
      if (res.success) {
        const { fullname, employment, idcard, gender } = res.data;
        studentColumns.value = [
          {
            label: "姓名：",
            value: fullname + "(" + (gender == 0 ? "男" : "女") + ")"
          },
          {
            label: "工作单位：",
            value: employment
          },
          {
            label: "证件号码：",
            value: idcard
          }
        ];
      }
    });
  }

  const formExamRef = ref();
  const formExamData = ref<FormExamProps>({
    id: -1,
    questionid: "",
    type: -1,
    score: 0,
    paperid: "",
    childIndex: -1,
    childId: "",
    childType: -1,
    title: "",
    childTitle: "",
    choiceList: []
  });
  const currentAnswerIdRef = ref(-1);
  const currentAnswerRef = ref(-1);
  watch(currentAnswerRef, newValue => {
    if (newValue < 0) {
      return;
    }
    if (newValue >= answerSheetList.value.length) {
      return;
    }

    const item = answerSheetList.value[currentAnswerRef.value];
    findProducePaperQuestionById(item).then(res => {
      if (res.success) {
        currentAnswerIdRef.value = res.data.id;
        formExamData.value = res.data;
      } else {
        message("考试异常:" + res.errMsg, { type: "error" });
      }
    });
  });

  function onAnswerChange() {
    //改变值监听，答案需要入库
    updateStudentProduceExamAnswer(formExamData.value).then(res => {
      if (res.success) {
        answerSheetList.value[currentAnswerRef.value] = formExamData.value;
      } else {
        message("答题异常:" + res.errMsg, { type: "error" });
      }
    });
  }

  const isStartExamRef = ref(false);

  async function onStartExam() {
    if (!window.EventSource) {
      message("浏览器版本太低，请更换浏览器!", { type: "error" });
      return;
    }
    if (!isOpenCameraRef.value) {
      message("开始答题前请打开摄像头", { type: "error" });
      return;
    }
    ElMessageBox.confirm("确认要开始答题？", "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true,
      closeOnClickModal: false
    })
      .then(() => {
        onStartExamByStudent({
          taskId: taskRef.value.id,
          paperid: taskRef.value.paperid
        }).then(res => {
          if (res.success) {
            answerSheetList.value = res.data;
            currentAnswerRef.value = 0;
            currentAnswerIdRef.value = 0;
            isStartExamRef.value = true;
            countDown().start(res.times * 60);
            createSSE();
          } else {
            // message("开始考试异常:" + res.errMsg, { type: "error" });
            onShowError("系统提示", "考试异常:" + res.errMsg);
          }
        });
      })
      .catch(() => {
        /**没有事情 */
      });
  }

  async function onStopExam() {
    ElMessageBox.confirm("是否要提交试卷？", "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true,
      closeOnClickModal: false
    })
      .then(() => {
        onStopExamByStudent({
          taskId: taskRef.value.id,
          paperid: taskRef.value.paperid,
          answerSheetList: answerSheetList.value
        }).then(res => {
          if (res.success) {
            const { score } = res;
            closeExamPage("系统提示", score);
          } else {
            message("结束考试异常:" + res.errMsg, { type: "error" });
          }
        });
      })
      .catch(() => {
        /**没有事情 */
      });
  }

  watch(showTime, value => {
    if (value <= 0) {
      if (isShowStopDialog.value) {
        return;
      }
      isShowStopDialog.value = true;

      onStopExamByStudent({
        taskId: taskRef.value.id,
        paperid: taskRef.value.paperid,
        answerSheetList: answerSheetList.value
      }).then(res => {
        if (res.success) {
          const { score } = res;
          closeExamPage("系统提示:自动交卷", score);
        } else {
          message("结束考试异常:" + res.errMsg, { type: "error" });
        }
      });
    }
  });

  async function onShowError(title, content) {
    isStartExamRef.value = false;
    ElMessageBox.confirm(content, title, {
      distinguishCancelAndClose: true,
      showCancelButton: false,
      closeOnClickModal: false,
      showClose: false,
      type: "error",
      center: true
    })
      .then(() => {
        emitter.emit("onSearchEmit");
        closeAllDialog();
      })
      .catch(() => {
        closeAllDialog();
      });
  }

  async function closeExamPage(title, score) {
    isStartExamRef.value = false;
    ElMessageBox.confirm("本次考试得分：" + score, title, {
      distinguishCancelAndClose: true,
      showCancelButton: false,
      closeOnClickModal: false,
      showClose: false,
      type: "success",
      center: true
    })
      .then(() => {
        emitter.emit("onSearchEmit");
        closeAllDialog();
      })
      .catch(() => {
        closeAllDialog();
      });
  }

  async function onPreQuestion() {
    if (currentAnswerRef.value <= 0) {
      return;
    }
    currentAnswerRef.value--;

    computedNumber();
  }

  async function onNextQuestion() {
    if (currentAnswerRef.value >= answerSheetList.value.length - 1) {
      return;
    }
    currentAnswerRef.value++;

    computedNumber();
  }

  function preventRightClick(event) {
    event.preventDefault();
  }

  const isOpenCameraRef = ref(false);
  const videoCameraRef = ref(null);
  const constraints = {
    audio: false,
    video: {
      width: 250,
      height: 250,
      transform: "scaleX(-1)"
    }
  };

  async function openCamera() {
    videoCameraRef.value = document.getElementById("videoCamera");
    try {
      const stream = await navigator.mediaDevices.getUserMedia(constraints);
      videoCameraRef.value.srcObject = stream;
      isOpenCameraRef.value = true;
    } catch (error) {
      console.log(error);
      /**没有事情可做 */
      ElMessageBox.confirm("没有开启摄像头权限或浏览器版本不兼容", "系统提示", {
        distinguishCancelAndClose: true,
        showCancelButton: false,
        closeOnClickModal: false,
        type: "error",
        center: true
      })
        .then(() => {
          closeAllDialog();
        })
        .catch(() => {
          closeAllDialog();
        });
    }
  }

  function closeCamera() {
    try {
      if (videoCameraRef.value && videoCameraRef.value !== null) {
        const stream = videoCameraRef.value.srcObject;
        if (stream != null) {
          const tracks = stream.getTracks();
          tracks.forEach(function (track) {
            track.stop();
          });
        }
        videoCameraRef.value.srcObject = null;
      }
    } catch (error) {
      /**没有事情可做 */
    }
    isOpenCameraRef.value = false;
  }

  const eventSourceRef = ref(null);

  async function createSSE() {
    if (window.EventSource) {
      const eventSource = new EventSourcePolyfill(sseUrlApi("createSse"), {
        heartbeatTimeout: 60 * 60 * 1000, //1小时后超时?
        headers: {
          Authorization: `Bearer ${getToken().accessToken}`
        }
      });
      eventSource.onopen = event => {
        console.log("onopen", event);
      };
      eventSource.onmessage = event => {
        console.log("onmessage", JSON.stringify(event));
        const json_data = JSON.parse(event.data);
        if (json_data.evenType === "EXMP000001") {
          if (isShowStopDialog.value) {
            return;
          }
          isShowStopDialog.value = true;
          closeExamPage("系统提示:自动交卷", json_data.score);
        } else if (json_data.evenType === "TAKEPHOTO") {
          takePhoto();
        }
      };
      eventSource.onerror = event => {
        console.log("onerror", event);
        if (event.readyState == EventSource.CLOSED) {
          console.log("SSE连接关闭");
        } else if (eventSource.readyState == EventSource.CONNECTING) {
          console.log("SSE正在重连");
          eventSource.headers = {
            Authorization: `Bearer ${getToken().accessToken}`
          };
        }
      };
      eventSourceRef.value = eventSource;
    }
  }

  function takePhoto() {
    if (!videoCameraRef.value) return;
    const canvas = document.createElement("canvas");
    canvas.width = videoCameraRef.value.videoWidth;
    canvas.height = videoCameraRef.value.videoHeight;
    //拿到 canvas 上下文对象
    const ctx = canvas.getContext("2d");
    ctx?.drawImage(videoCameraRef.value, 0, 0, canvas.width, canvas.height);
    const dataURL = canvas.toDataURL();

    sendPhoto({
      taskId: taskRef.value.id,
      photo: dataURL
    }).then(res => {
      console.log(JSON.stringify(res));
    });
  }

  async function closeSSE() {
    if (eventSourceRef.value && eventSourceRef.value != null) {
      eventSourceRef.value.close();
      eventSourceRef.value = null;
      closeSseClient().then(_res => {});
    }
  }

  onMounted(() => {
    isShowStopDialog.value = false;
    isOpenCameraRef.value = true; //测试默认打开
    openCamera();
    onGetUserInfo();
    // 阻止右键菜单的默认行为
    window.addEventListener("contextmenu", preventRightClick);
  });

  onUnmounted(() => {
    isShowStopDialog.value = false;
    closeSSE();
    closeCamera();
    // 移除事件监听器
    window.removeEventListener("contextmenu", preventRightClick);
  });

  const showIdRef = ref("01");

  const answerSheetList0 = computed(() => {
    return answerSheetList.value.filter(item => item.type === 0);
  });

  const answerSheetList1 = computed(() => {
    return answerSheetList.value.filter(item => item.type === 1);
  });

  const answerSheetList2 = computed(() => {
    return answerSheetList.value.filter(item => item.type === 2);
  });

  const answerSheetList3 = computed(() => {
    return answerSheetList.value.filter(item => item.type === 3);
  });

  function computedNumber() {
    const size0 = currentAnswerRef.value - answerSheetList0.value.length;
    if (size0 < 0) {
      showIdRef.value = showMumber(currentAnswerRef.value);
      return;
    }
    const size1 =
      currentAnswerRef.value -
      answerSheetList0.value.length -
      answerSheetList1.value.length;
    if (size1 < 0) {
      showIdRef.value = showMumber(
        currentAnswerRef.value - answerSheetList0.value.length
      );
      return;
    }

    const size2 =
      currentAnswerRef.value -
      answerSheetList0.value.length -
      answerSheetList1.value.length -
      answerSheetList2.value.length;
    if (size2 < 0) {
      showIdRef.value = showMumber(
        currentAnswerRef.value -
          answerSheetList0.value.length -
          answerSheetList1.value.length
      );
      return;
    }

    const size3 =
      currentAnswerRef.value -
      answerSheetList0.value.length -
      answerSheetList1.value.length -
      answerSheetList2.value.length -
      answerSheetList3.value.length;
    if (size3 < 0) {
      showIdRef.value = showMumber(
        currentAnswerRef.value -
          answerSheetList0.value.length -
          answerSheetList1.value.length -
          answerSheetList2.value.length
      );
      return;
    }
  }

  function showMumber(index) {
    if (index < 9) {
      return "0" + (index + 1);
    } else {
      return index + 1;
    }
  }

  return {
    constraints,
    isStartExamRef,
    studentColumns,
    setFormInlineToTsx,
    answerSheetList,
    onStartExam,
    onStopExam,
    formExamRef,
    formExamData,
    onPreQuestion,
    onNextQuestion,
    currentAnswerRef,
    currentAnswerIdRef,
    onAnswerChange,
    countDown,
    showTime,
    showIdRef,
    showMumber,
    answerSheetList0,
    answerSheetList1,
    answerSheetList2,
    answerSheetList3
  };
}
